//
//  DealWithBackLogViewController.m
//  代办事宜
//
//  Created by wang on 12-8-24.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import "DealWithBackLogViewController.h"
#import "OrgEmpViewController.h"
#import "UIViewPassValueDelegate.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "JSONKit.h"
#import "MainViewController.h"

@interface DealWithBackLogViewController ()<UITextFieldDelegate,UITextViewDelegate,UIViewPassValueDelegate,ASIHTTPRequestDelegate,UIWebViewDelegate,UIPickerViewDataSource,UIPickerViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property (strong,nonatomic)UITextField* selectText;
@property (strong,nonatomic)UIButton* selectButton;
@property (strong,nonatomic)UITextField* selectText4guding;
@property (strong,nonatomic)UIPickerView* selectPick4guding;
@property (strong,nonatomic)UIButton* selectButton4guding;
@property (strong,nonatomic)UITextView* tempText4suggest;
@property (strong,nonatomic)UIButton* tempAgreeButton;
@property (strong,nonatomic)UIButton* tempNotAgreeButton;
@property (strong,nonatomic)NSString* selectTextValue;
@property (strong,nonatomic)UISwitch* tempSwitch;
@property (strong,nonatomic)NSString* eventId;
@property (strong,nonatomic)NSDictionary* eventObjDictory;
@property (nonatomic, strong) UIAlertView *alertSuccess;
@property (nonatomic, strong) NSDictionary* empInfo;
@property (nonatomic, strong) UIAlertView *alertWarn;
@property (nonatomic, strong) UIToolbar*toolbar4guding;


@end

@implementation DealWithBackLogViewController
@synthesize selectText=_selectText;
@synthesize selectButton=_selectButton;
@synthesize selectText4guding=_selectText4guding;
@synthesize selectButton4guding=_selectButton4guding;
@synthesize selectPick4guding=_selectPick4guding;
@synthesize tempText4suggest=_tempText4suggest;
@synthesize tempAgreeButton=_tempAgreeButton;
@synthesize tempNotAgreeButton=_tempNotAgreeButton;
@synthesize selectTextValue=_selectTextValue;
@synthesize tempSwitch=_tempSwitch;
@synthesize eventId=_eventId;
@synthesize eventObjDictory=_eventObjDictory;
@synthesize alertSuccess=_alertSuccess;
@synthesize empInfo=_empInfo;
@synthesize alertWarn=_alertWarn;
@synthesize toolbar4guding=_toolbar4guding;
NSString *resultHtml;
NSArray*ar;
NSDictionary*empOrg;

//delegate实现方法
-(void)passOrgEmpValue:(NSDictionary*)v{
    NSString*name=[v objectForKey:@"userName"];
    if(name!=nil||![name isEqualToString:@""])
    {
        self.selectTextValue=name;
        self.empInfo=v;
    }
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title=@"事务处理";  
    UITableView*myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width,
                                                                         self.view.bounds.size.height)
                                                        style:UITableViewStyleGrouped];
    [myTableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    [myTableView setDelegate:self];
    [myTableView setDataSource:self];
    [self.view addSubview: myTableView];
        
//    bt覆盖backgroud监听键盘
//    UIButton*backGroundBt=[UIButton buttonWithType:UIButtonTypeCustom];
//    [backGroundBt setFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
//    [backGroundBt addTarget:self action:@selector(clickBackGround:) forControlEvents:UIControlEventTouchUpInside];
//    [myTableView addSubview:backGroundBt];

    
    //固定流程处理人
    self.toolbar4guding=[[UIToolbar alloc] initWithFrame:CGRectMake(0, 755, 100, 40)];
    [self.toolbar4guding sizeToFit];
    self.toolbar4guding.autoresizingMask = UIViewAutoresizingFlexibleWidth;//这句作用是切换时宽度自适应.
    UIBarButtonItem* barItem1 = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonSystemItemAction  target:self action:@selector(saveOrgEmp4guding:)];
    UIBarButtonItem* barItem2 = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonSystemItemAction  target:self action:@selector(cannelOrgEmp4guding:)];
    NSMutableArray*items=[[NSMutableArray alloc] initWithCapacity:3];
    [items addObject:barItem1];
    [items addObject:barItem2];
    
    [self.toolbar4guding setItems:items animated:YES];
    [self.toolbar4guding setHidden:YES];
    [self.view addSubview:self.toolbar4guding]; 
    
    self.selectPick4guding=[[UIPickerView alloc] initWithFrame:CGRectMake(0, 798, self.view.bounds.size.width, 150)];
    self.selectPick4guding.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    self.selectPick4guding.dataSource = self;
    self.selectPick4guding.delegate = self; 
    self.selectPick4guding.showsSelectionIndicator = YES; 
    [self.selectPick4guding setHidden:YES];
    [self.view addSubview:self.selectPick4guding];
    
}

- (void)viewDidAppear:(BOOL)animated {
    
    if(![[self.eventObjDictory objectForKey:@"anyFlag"] isEqualToString:@"Y"]){
        NSString* u=[[NSUserDefaults standardUserDefaults]objectForKey:@"WebserviceUrl"];
        NSURL *url = [NSURL URLWithString:u];    
        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];    
        [request addPostValue: @"gotoDealWith" forKey:@"method"];
        [request addPostValue: [self.eventObjDictory objectForKey:@"eventId"] forKey:@"eventId"];
        [request startSynchronous];
        NSError *error = [request error];
        if (!error) {
            resultHtml = [request responseString];
            ar= [resultHtml objectFromJSONString];
            //不支持路由或是无处理人
            if(ar==nil){
                if([resultHtml isEqualToString:@"END"]){
                    NSLog(@"无处理人，尾节点");
                }else {
                self.view.hidden=YES;
                self.alertWarn = [[UIAlertView alloc] initWithTitle:@"事务处理" message:resultHtml
                                                               delegate:self cancelButtonTitle:nil otherButtonTitles: @"OK",nil];
                [self.alertWarn show];   
                }
            }else {
                NSDictionary*dic1=[ar objectAtIndex:0];
                //岗位
                [self.selectText4guding setText:[dic1 objectForKey:@"stationName"]];
            }
        }

        
    }else {
        [self.selectText setText:self.selectTextValue];
    }
    [self.selectPick4guding reloadAllComponents];
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section==0) {
        if(![[self.eventObjDictory objectForKey:@"anyFlag"] isEqualToString:@"Y"])
        {
            return @"处理角色";
        }
        else {
            return @"继续处理";
        }
    }else if(section==1){
        return @"处理人";
    }else {
        return @"处理意见";
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if(section==2){
        return 2;
    }else {
        return 1;
    }
}

//row高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if(indexPath.section==2)
    {
        if(indexPath.row==0){
        return 500;
        }else {
            return 120;
        }
    }else {
        return 80;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString* CellIdentifier = [NSString stringWithFormat:@"%d%d",indexPath.section, indexPath.row];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    for (UIView *v in [cell subviews]) {
        if ([v isKindOfClass:[UILabel class]] |
            [v isKindOfClass:[UITextView class]]) {
            [v removeFromSuperview];
        }
    }   
    if(indexPath.section==0){
        
        if(![[self.eventObjDictory objectForKey:@"anyFlag"] isEqualToString:@"Y"]){
            
            //岗位文本
            self.selectText4guding = [[UITextField alloc] initWithFrame:CGRectMake(60, 10, 630, 60)];  
            [self.selectText4guding setDelegate:self];
            self.selectText4guding.backgroundColor=[UIColor lightTextColor];
            self.selectText4guding.layer.borderColor = [[UIColor brownColor] CGColor];//设置边框的颜色
            self.selectText4guding.layer.borderWidth =1.0;
            self.selectText4guding.layer.cornerRadius =5.0; 
            [self.selectText4guding setTextAlignment:UITextAlignmentCenter];
            self.selectText4guding .font = [UIFont fontWithName:@"Marker Felt" size:36];            [cell addSubview:self.selectText4guding];
            
            //处理人选择按钮固定
            self.selectButton4guding= [UIButton buttonWithType:UIButtonTypeContactAdd];
            [self.selectButton4guding setFrame:CGRectMake(680, 25, 50, 30)];
            [self.selectButton4guding setBackgroundColor:[UIColor clearColor]];
            [self.selectButton4guding addTarget:self action:@selector(selectOrgEmp4guding:) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:self.selectButton4guding];
            
            
        }else {
                       
            //是否继续处理按钮
            self.tempSwitch=[[UISwitch alloc] initWithFrame:CGRectMake(320, 30, 0, 0)];
            [self.tempSwitch addTarget:self action:@selector(selectOperatorDisplay:) forControlEvents:UIControlEventValueChanged];
            self.tempSwitch.backgroundColor = [UIColor clearColor];
            [self.tempSwitch setOn:NO];
            [cell addSubview:self.tempSwitch];

        }

    }else if (indexPath.section==1) {
        
        if(![[self.eventObjDictory objectForKey:@"anyFlag"] isEqualToString:@"Y"]){
            
            //处理人文本
            self.selectText = [[UITextField alloc] initWithFrame:CGRectMake(60, 10, 630, 60)];  
            [self.selectText setDelegate:self];
            self.selectText.backgroundColor=[UIColor lightTextColor];
            self.selectText.layer.borderColor = [[UIColor brownColor] CGColor];//设置边框的颜色
            [self.selectText setText:self.selectTextValue];
            self.selectText.layer.borderWidth =1.0;
            self.selectText.layer.cornerRadius =5.0; 
            [self.selectText setTextAlignment:UITextAlignmentCenter];
            self.selectText .font = [UIFont fontWithName:@"Marker Felt" size:36];
            [cell addSubview:self.selectText];

        
        }else {
            //处理人文本
            self.selectText = [[UITextField alloc] initWithFrame:CGRectMake(60, 10,630,60)];  
            [self.selectText setDelegate:self];
            self.selectText.backgroundColor=[UIColor lightTextColor];
            self.selectText.layer.borderColor = [[UIColor brownColor] CGColor];//设置边框的颜色
            [self.selectText setText:self.selectTextValue];
            self.selectText.layer.borderWidth =1.0;
            self.selectText.layer.cornerRadius =5.0; 
            [self.selectText setTextAlignment:UITextAlignmentCenter];
            self.selectText .font = [UIFont fontWithName:@"Marker Felt" size:36];
            [cell addSubview:self.selectText];
            
            //处理人选择按钮
            self.selectButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
            [self.selectButton setFrame:CGRectMake(680, 25, 50, 30)];
            [self.selectButton setBackgroundColor:[UIColor clearColor]];
            [self.selectButton addTarget:self action:@selector(selectOrgEmp:) forControlEvents:UIControlEventTouchUpInside];
            [self.selectButton setHidden:YES];
            [cell addSubview:self.selectButton];
        }
        
        
    }else if (indexPath.section==2) {
        if(indexPath.row==0){
        //处理意见文本
        self.tempText4suggest = [[UITextView alloc] initWithFrame:CGRectMake(60, 10, 630, 460)];  
        self.tempText4suggest.backgroundColor=[UIColor lightTextColor];
        self.tempText4suggest .font = [UIFont fontWithName:@"Marker Felt" size:36];
        self.tempText4suggest .textColor = [UIColor colorWithWhite:0.200 alpha:1.000]; 
        self.tempText4suggest.layer.borderColor = [[UIColor brownColor] CGColor];//设置边框的颜色
        self.tempText4suggest.returnKeyType = UIReturnKeyDone;  
        self.tempText4suggest.delegate = self;  

        [cell addSubview:self.tempText4suggest];
        }else {
            self.tempAgreeButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
            self.tempAgreeButton.frame=CGRectMake(100, 30, 200, 60);
            [self.tempAgreeButton setTitle:@"同意" forState:UIControlStateNormal];
            [self.tempAgreeButton addTarget:self action:@selector(agree:) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:self.tempAgreeButton];
            
            self.tempNotAgreeButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
            self.tempNotAgreeButton.frame=CGRectMake(450, 30, 200, 60);
            [self.tempNotAgreeButton setTitle:@"拒绝" forState:UIControlStateNormal];
            [self.tempNotAgreeButton addTarget:self action:@selector(notAgree:) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:self.tempNotAgreeButton];

        }

    }
    return cell;
    
}

//选择处理人显示
-(void) selectOperatorDisplay:(id) sender{
    if([sender isOn]){
        self.selectButton.hidden=NO;
            
    }else{
        self.selectButton.hidden=YES;
       
    }
}

//任意  选人组织
-(void)selectOrgEmp:(id)sender{
    OrgEmpViewController*orgEmpController=[[OrgEmpViewController alloc] init];
    orgEmpController.delegate=self;
    [self.navigationController pushViewController:orgEmpController animated:YES];
}
//固定  选人组织
-(void)selectOrgEmp4guding:(id)sender{
        [self.selectPick4guding setHidden:NO];
        [self.toolbar4guding setHidden:NO];
}

-(void)saveOrgEmp4guding:(id)sender{
    
    [self.selectText setText:[empOrg objectForKey:@"userName"]];
    self.selectPick4guding.hidden = YES;	
    self.toolbar4guding.hidden=YES;
    
}
-(void)cannelOrgEmp4guding:(id)sender{

        self.selectPick4guding.hidden = YES;	
        self.toolbar4guding.hidden=YES;
}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField; {
    return NO; 
} 
- (void)textViewDidBeginEditing:(UITextView *)textView{
    //NSLog(@"textview did begin editing");
    //键盘遮住了文本字段，视图整体上移
    
    [UIView beginAnimations:nil context:nil]; // begins animation block
    [UIView setAnimationDuration:0.5];        // sets animation duration
    
    CGRect frame = self.view.frame;  
    frame.origin.y -=216;  
    frame.size.height +=216;  
    self.view.frame = frame; 
    
    [UIView commitAnimations];   // commits the animation block.  This Block is done.
    
}


-(void)textViewDidEndEditing:(UITextView *)textView{
    //NSLog(@"textview did end editing");
    
    [UIView beginAnimations:nil context:nil]; // begins animation block
    [UIView setAnimationDuration:0.5];        // sets animation duration
    //之前视图上移了  现在移回来 
    CGRect frame = self.view.frame;  
    frame.origin.y +=216;  
    frame.size.height -=216;  
    self.view.frame = frame;    
    
    [UIView commitAnimations];   // commits the animation block.  This Block is done.
}

//textView回收键盘
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text  
{  
    if ([@"\n" isEqualToString:text] == YES)  
    {  
        [self.tempText4suggest resignFirstResponder];  
        return NO;  
    }      
    return YES;  
} 


-(void)clickBackGround:(id)sender{
    [self.tempText4suggest resignFirstResponder];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void) agree:(id) sender{
    
    [self showMbprogress];
    NSString* u=[[NSUserDefaults standardUserDefaults]objectForKey:@"WebserviceUrl"];
    NSURL *url = [NSURL URLWithString:u];    
    ASIFormDataRequest *agreeRequest = [ASIFormDataRequest requestWithURL:url];    
    [agreeRequest addPostValue: @"agreeEvent" forKey:@"method"];
    [agreeRequest addPostValue:[self.eventObjDictory objectForKey:@"modelId"] forKey:@"modelId"];
    [agreeRequest addPostValue:self.eventId forKey:@"eventId"];
    [agreeRequest addPostValue:[self.empInfo objectForKey:@"userId"] forKey:@"nextUserId"];
    [agreeRequest addPostValue:[self.empInfo objectForKey:@"orgId"] forKey:@"nextOrgId"];
    if(!self.tempSwitch.on )
    [agreeRequest addPostValue:@"E" forKey:@"chooseFlag"];//任意流程尾节点
    [agreeRequest addPostValue:[self.eventObjDictory objectForKey:@"anyFlag"]  forKey:@"anyFlag"];//Y为任意流程
    if([resultHtml isEqualToString:@"END"])
    [agreeRequest addPostValue:@"E" forKey:@"choosePoint"];//固定流程尾节点
    [agreeRequest addPostValue:[empOrg objectForKey:@"userId"] forKey:@"userId"];
    [agreeRequest addPostValue:[empOrg objectForKey:@"stationId"] forKey:@"stationId"];
    [agreeRequest addPostValue:[empOrg objectForKey:@"orgId"] forKey:@"orgId"];
    [agreeRequest addPostValue:[empOrg objectForKey:@"nextModelDetailId"] forKey:@"nextModelDetailId"];
    [agreeRequest addPostValue:[empOrg objectForKey:@"curModelDetailId"] forKey:@"curModelDetailId"];
    [agreeRequest addPostValue:[empOrg objectForKey:@"count"] forKey:@"count"];
    [agreeRequest addPostValue:self.tempText4suggest.text forKey:@"memo"];
    [agreeRequest setDelegate:self];
    [agreeRequest start];
    
    
}


-(void) notAgree:(id) sender{
    
    [self showMbprogress];
    NSString* u=[[NSUserDefaults standardUserDefaults]objectForKey:@"WebserviceUrl"];
    NSURL *url = [NSURL URLWithString:u];    
    ASIFormDataRequest *notAgreeRequest = [ASIFormDataRequest requestWithURL:url]; 
    [notAgreeRequest addPostValue: @"notAgreeEvent" forKey:@"method"];
    [notAgreeRequest addPostValue:self.eventId forKey:@"eventId"];
    [notAgreeRequest addPostValue:self.tempText4suggest.text forKey:@"memo"];
    [notAgreeRequest setDelegate:self];
    [notAgreeRequest start];
}


- (void)requestFinished:(ASIHTTPRequest *)request {
       
    NSError *error = [request error];
    if ((!error)&&request) {
        NSString *res = [request responseString];
        NSLog(@"%@",res);
        [self hideMbProgress];
        if([res isEqualToString:@"true"]){
        self.alertSuccess = [[UIAlertView alloc] initWithTitle:@"事务处理" message:@"处理成功!"
                                                       delegate:self cancelButtonTitle:nil otherButtonTitles: @"OK",nil];
        [ self.alertSuccess show];
        }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"事务处理" message:@"处理失败!请稍后再试,或直接联系系统管理员!"
                                                           delegate:self cancelButtonTitle:nil otherButtonTitles: @"OK",nil];
        [alert show];
        }
    }        
   
    
}

//处理人
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{    
    return [ar count];
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{   
    NSDictionary*temp=[ar objectAtIndex:row];
    return [NSString stringWithFormat:@"%@",[temp objectForKey:@"userName"]];
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
    NSDictionary*temp=[ar objectAtIndex:row];
    NSString* userName=[temp objectForKey:@"userName"]; 
    empOrg=temp;
    NSLog(@"%@ is selected.",userName);
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if((alertView == self.alertSuccess)||(alertView == self.alertWarn))
    {
        //回代办首页
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}

-(void)passEventObjFromDetail:(NSDictionary*) totalDictory
{
    self.eventId=[totalDictory objectForKey:@"eventId"];
    self.eventObjDictory=totalDictory;
}

@end
